<!-- 抽奖首页 -->
<template>
  <view class="lottery-container">
    <view class="topbox">
      <view class="lwbox">
        <u-image
          src="./static/lw.png"
          width="260rpx"
          height="250rpx"
          mode="widthFix"
        ></u-image>
      </view>
      <view class="bjbox">
        <view class="lottery-grid">
          <!-- 按照图1的顺序排列，第5个位置是按钮 -->
          <view
            v-for="(ele, index) in prizeList"
            :key="index"
            :class="[
              'lottery-item',
              {
                active: activeIndex === index,
                'draw-button': index === 4,
                disabled: index === 4 && (isDrawing || hasDrawn)
              }
            ]"
            :disabled="index === 4 && (isDrawing || hasDrawn)"
            @click="handleItemClick(index)"
          >
            <view class="item-content">
              <view v-if="index === 4" class="draw-button-content">
                <view class="button-text">{{
                  hasDrawn == true ? '已抽奖品' : '立即抽奖'
                }}</view>
              </view>
              <view v-else class="prize-content">
                <view class="prize-tp">
                  <u-image
                    src="./static/jp.png"
                    width="100rpx"
                    height="100rpx"
                  ></u-image>
                </view>
                <view class="prize-name">{{ ele.name }}</view>
                <view class="prize-desc" v-if="ele.desc">{{ ele.desc }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="bottombox">
      <!-- 抽奖说明展示 -->
      <view class="xhz">
        <view class="bt">
          <u-image
            src="./static/bt1.png"
            width="320rpx"
            height="60rpx"
          ></u-image>
        </view>
        <view class="nr">
          <view> 1.下单并支付成功即可抽奖一次</view>
          <view style="margin: 10rpx 0"> 2.抽奖现场领取奖品，凭手机号兑奖</view>
          <view style="margin: 10rpx 0"> 3.最终解释权归商家所有</view>
          <view style="color: red">
            4.抽奖机会仅限本次消费使用，若不使用则视为自愿放弃该次机会，抽奖资格将自动作废</view
          >
        </view>
      </view>
      <!-- 中奖名单展示 -->
      <view class="xhz" v-if="winPrizeList.length > 0">
        <view class="bt"
          ><u-image
            src="./static/bt2.png"
            width="320rpx"
            height="60rpx"
          ></u-image
        ></view>
        <view class="nr" style="height: 180rpx; overflow-y: scroll">
          <view
            v-for="ele in winPrizeList"
            style="
              width: 500rpx;
              display: flex;
              margin: 0 auto;
              margin-bottom: 10rpx;
              justify-content: space-around;
            "
          >
            <view>恭喜{{ ele.phone }}</view> <view>获得{{ ele.name }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 恭喜中奖弹框 -->
    <u-modal
      v-model="showSuccess"
      :show-title="false"
      :show-cancel-button="false"
      @confirm="handleCloseSuccess"
    >
      <view style="text-align: center; padding: 20rpx">
        <view style="display: flex; justify-content: center; margin: 20rpx 0"
          ><u-image src="./static/jp.png" width="80rpx" height="80rpx"></u-image
        ></view>
        <view style="font-size: 40rpx"
          >恭喜抽中<span style="color: red">{{ successContent }}</span></view
        >
        <view style="margin-top: 20rpx; color: #999">请凭手机号现场兑奖</view>
      </view>
    </u-modal>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from 'vue'
import { onLoad, onShow, onReady, onUnload, onHide } from '@dcloudio/uni-app'
import { couponApi } from '@/api'
const showSuccess = ref(false)
const successContent = ref('')
// 中奖记录列表
const winPrizeList = ref<any>([])
// 按照图1的顺序定义9个格子，第5个是按钮
const prizeList = ref<any[]>([])
const shopId = ref(0)
// 当前高亮的格子索引
const activeIndex = ref<number>(-1)
// 抽奖状态
const isDrawing = ref<boolean>(false)
const isApp = ref(false)
// 定义顺时针转动路径 (外层8个格子的索引顺序)
const clockwisePath = [0, 1, 2, 5, 8, 7, 6, 3]
// 新增：会话标识相关
const sessionKey = ref('')
const hasDrawn = ref<boolean>(false)

onLoad(async (option: any) => {
  console.log('进入onload')
  if (option?.from && option.from.toLowerCase() === 'app') {
    isApp.value = true
  } else {
    isApp.value = false
  }
  if (option.shopId) {
    shopId.value = option.shopId
  } else {
    uni.showToast({ title: '缺乏商家id', icon: 'none' })
    return
  }
  initSessionAndDrawStatus()
  await handleGetPrizeList()
  await handleGetWinPrizeList()
})
// 退出页面onUnload onHide会提前执行remove操作
onUnload(() => {
  console.log('离开抽奖页面')
  uni.removeStorageSync(`lottery_session_${shopId.value}`)
  uni.removeStorageSync(`lottery_drawn_${shopId.value}`)
  hasDrawn.value = false
})
// 获取奖品列表
const handleGetPrizeList = async () => {
  try {
    const { data } = await couponApi.handleGetPrizeListAPi({
      shopId: shopId.value
    })
    console.log('获取奖品列表', data)
    if (data.records.length > 0) {
      prizeList.value = data.records
      prizeList.value.splice(4, 0, { id: '000', name: '' })
      console.log('prizeList', prizeList.value)
    }
  } catch (error) {
    console.log('获取奖品列表失败')
  }
}
// 获取中奖记录列表
const handleGetWinPrizeList = async () => {
  try {
    const { data } = await couponApi.handleGetWinPrizeRecordListApi({
      shopId: shopId.value,
      noPaging: true
    })
    console.log('获取中奖记录列表', data)
    if (data.length > 0) {
      winPrizeList.value = data.map((ele: any) => {
        return {
          ...ele,
          phone: ele.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        }
      })
      // console.log('winPrizeList', winPrizeList.value)
    } else {
      winPrizeList.value = []
    }
  } catch (error) {
    console.log('获取中奖记录列表失败')
  }
}

// 初始化会话标识和抽奖状态
const initSessionAndDrawStatus = () => {
  const storedSession = uni.getStorageSync(`lottery_session_${shopId.value}`)
  const storedDrawn = uni.getStorageSync(`lottery_drawn_${shopId.value}`)
  if (storedSession) {
    console.log('jin11')
    // 复用已有会话
    sessionKey.value = storedSession
    hasDrawn.value = storedDrawn == 'true' // 同步本地状态到响应式变量
  } else {
    console.log('jin22')
    // 新会话：生成新标识并初始化状态
    sessionKey.value = `lottery_${Date.now()}_${Math.random()
      .toString(36)
      .slice(-8)}`
    uni.setStorageSync(`lottery_session_${shopId.value}`, sessionKey.value)
    hasDrawn.value = false // 新会话默认未抽奖
  }
}

// 处理格子点击
const handleItemClick = (index: number) => {
  if (index === 4 && !isDrawing.value) {
    // 点击开始抽奖按钮
    handleStartLottery()
  }
}
// 确定中奖下标
const handleGetWinIndex = async (): Promise<number> => {
  try {
    const { data } = await couponApi.handleGetWinPrizeApi({
      shopId: shopId.value
    })
    // 假设接口返回中奖奖品的索引（或根据奖品ID计算索引）
    const winPrizeId = data.id
    const finalIndex = prizeList.value.findIndex((ele) => ele.id === winPrizeId)
    return finalIndex !== -1 ? finalIndex : -1 // 兜底返回-1
  } catch (error) {
    console.log('获取中奖结果失败')
    return -1
  }
}
// 绘制动画
const handleDrawAnimation = async (targetIndex: number): Promise<void> => {
  return new Promise((resolve) => {
    const targetPathIndex = clockwisePath.indexOf(targetIndex)
    if (targetPathIndex === -1) {
      resolve()
      return
    }

    let currentPathIndex = 0
    let stepCount = 0
    const baseRounds = 3
    const totalSteps = clockwisePath.length * baseRounds + targetPathIndex
    const getSpeed = (progress: number) => {
      if (progress < 0.5) return 80
      if (progress < 0.7) return 120
      if (progress < 0.85) return 200
      if (progress < 0.95) return 350
      return 600
    }
    // 核心修复：先判断是否完成，再更新位置
    const animate = () => {
      // 先检查是否已到达总步数
      if (stepCount < totalSteps) {
        // 更新当前高亮位置（使用当前路径索引）
        activeIndex.value = clockwisePath[currentPathIndex]
        // 计算下一步路径索引
        currentPathIndex = (currentPathIndex + 1) % clockwisePath.length
        stepCount++
        // 继续动画
        const progress = stepCount / totalSteps
        setTimeout(animate, getSpeed(progress))
      } else {
        // 动画结束，强制定位到目标
        activeIndex.value = targetIndex
        nextTick(resolve)
      }
    }
    // 启动动画
    animate()
  })
}
// 开始抽奖
const handleStartLottery = async () => {
  if (hasDrawn.value) return
  if (isDrawing.value) return
  isDrawing.value = true
  try {
    // 步骤1：先获取中奖结果（关键！必须先知道目标位置）
    const finalIndex = await handleGetWinIndex()
    if (finalIndex === -1) {
      isDrawing.value = false
      return
    }
    // 步骤2：传入目标位置执行动画（确保路径计算准确）
    await handleDrawAnimation(finalIndex)
    // 步骤3：显示中奖结果
    successContent.value = prizeList.value[finalIndex].name
    showSuccess.value = true
    // 更新响应式变量和本地存储
    hasDrawn.value = true
    uni.setStorageSync(`lottery_drawn_${shopId.value}`, 'true')
  } catch (error) {
    console.error('抽奖过程出错:', error)
  } finally {
    isDrawing.value = false
  }
}
// 关闭成功弹框
const handleCloseSuccess = () => {
  showSuccess.value = false
  handleGetWinPrizeList()
  // uni.switchTab({
  //   url: '/pages/index/index'
  // })
}
</script>
<style lang="scss" scoped>
.lottery-container {
  background-image: url(./static/bj.png);
  background-repeat: no-repeat;
  min-height: 100vh;
  width: 750rpx;
  background-size: cover;
  padding: 20rpx;
  // position: relative;
}
.topbox {
  position: relative;
  margin-bottom: 40rpx;
  .lwbox {
    position: absolute;
    top: -170rpx;
    right: 5rpx;
    z-index: 2;
  }
  .bjbox {
    width: 700rpx;
    height: 700rpx;
    background-image: url(./static/bk.png);
    background-position: center center;
    background-size: cover;
    margin-top: 350rpx;
    position: relative;
  }

  .lottery-grid {
    background-color: #a31930;
    width: 650rpx;
    height: 650rpx;
    display: grid;
    grid-template-columns: repeat(3, 190rpx);
    grid-template-rows: repeat(3, 190rpx);
    gap: 20rpx;
    padding: 20rpx;
    position: absolute;
    top: 25rpx;
    left: 25rpx;
  }

  .lottery-item {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    border-radius: 8rpx;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    // 默认状态
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;

      opacity: 0;
      transition: opacity 0.3s ease;
    }

    &:hover::before {
      opacity: 1;
    }

    // 高亮状态 - 增强视觉效果
    &.active {
      background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
      transform: scale(1.08);
      box-shadow: 0 0 25rpx rgba(255, 107, 107, 0.8),
        0 0 15rpx rgba(255, 255, 255, 0.6) inset;
      z-index: 10;

      &::after {
        content: '';
        position: absolute;
        top: -3rpx;
        left: -3rpx;
        right: -3rpx;
        bottom: -3rpx;
        background: linear-gradient(45deg, #ffd700, #ff6b6b, #ff8e53, #ffd700);
        border-radius: 11rpx;
        z-index: -1;
        animation: borderGlow 0.8s ease-in-out infinite alternate;
      }

      // 高亮时的文字效果
      .item-content {
        color: #fff;
        text-shadow: 0 0 10rpx rgba(255, 255, 255, 0.8);
      }
    }

    // 抽奖按钮特殊样式
    &.draw-button {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      cursor: pointer;

      &:hover {
        transform: scale(1.05);
        box-shadow: 0 0 15rpx rgba(245, 87, 108, 0.4);
      }

      &:active {
        transform: scale(0.95);
      }

      // 按钮在高亮时也保持特殊样式
      &.active {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
      }
    }
    // 添加禁用状态样式
    &.disabled {
      opacity: 0.3;
      cursor: not-allowed;
      transform: none !important;
      box-shadow: none !important;

      &::after {
        display: none;
      }
    }
  }

  .item-content {
    text-align: center;
    color: white;
    z-index: 2;
    padding: 10rpx;
    transition: all 0.3s ease;
  }

  // 抽奖按钮内容
  .draw-button-content {
    width: 190rpx;
    height: 190rpx;
    background-color: #f74067;
    .button-text {
      font-size: 68rpx;
      font-weight: bold;
      text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.3);
    }
  }

  // 奖品内容
  .prize-content {
    color: #a31930;
    text-align: center;
    .prize-tp {
      display: flex;
      justify-content: center;
      margin-bottom: 10rpx;
    }
    .prize-name {
      font-size: 24rpx;
      margin-bottom: 4rpx;
      text-shadow: 1rpx 1rpx 2rpx rgba(0, 0, 0, 0.3);
    }

    .prize-desc {
      opacity: 0.9;
    }
  }

  // 边框发光动画 - 优化效果
  @keyframes borderGlow {
    0% {
      opacity: 0.7;
      filter: hue-rotate(0deg);
    }
    100% {
      opacity: 1;
      filter: hue-rotate(90deg);
    }
  }

  @keyframes bounce {
    0%,
    100% {
      transform: translateX(-50%) translateY(0);
    }
    50% {
      transform: translateX(-50%) translateY(-5rpx);
    }
  }

  // 响应式设计
  @media (max-width: 480rpx) {
    .lottery-grid {
      grid-template-columns: repeat(3, 100rpx);
      grid-template-rows: repeat(3, 100rpx);
    }

    .prize-content .prize-name {
      font-size: 12rpx;
    }

    .draw-button-content .button-text {
      font-size: 16rpx;
    }
  }
}
.bottombox {
  .xhz {
    width: 700rpx;
    background-color: #ffe9e2;
    border-radius: 20rpx;
    font-size: 28rpx;
    color: #a31930;
    padding: 20rpx;
    margin-bottom: 40rpx;
    padding-top: 0;
    .bt {
      display: flex;
      justify-content: center;
      margin-bottom: 20rpx;
    }
  }
}
</style>
